<!-- 班级统计 -->
<template>
    <div class="report" @scroll="scrollLoad()" ref="review">
        <div class="report-con">
            <div class="report-top clearfix">
                <span class="left" @click="classMaskShow=true">{{thisClass.name}}统计</span>
                <i class="right" @click="closeTask()" v-if="task.userId==userid">终止打卡</i>
            </div>
            <!-- 任务信息 -->
            <div class="task-book shadow3">
                <div class="book-box clearfix">
                    <img class="book-img shadow1 left" :src="book.bookCover" alt="">
                    <div class="book-info left">
                        <div class="task-name">{{book.bookName}}</div>
                        <div class="author">{{book.gradeName}} · {{book.bookCountry}} · {{book.bookAuthor}}</div>
                        <ul class="task-read clearfix">
                            <li class="task-day left">
                                <em>{{countday}}/{{task.dayCount}}</em>
                                <span>打卡天数</span>
                            </li>
                            <li class="task-time left">
                                <em>{{task.takeMinute}}分钟</em>
                                <span>阅读时长</span>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="todaynum" @click="goToday()">今日已完成{{complete.length}}人</div>
            </div>
            <!-- 统计图表 -->
            <div class="chart">
                <div class="chart-box shadow3 chart-number">
                    <h4>每日完成人数</h4>
                    <div class="chart-card">
                        <div id="chart-number" :style="'width:'+ numElapseP"></div>
                    </div>
                </div>
                <div class="chart-box shadow3 chart-duration">
                    <h4>阅读平均时长</h4>
                    <div class="chart-card">
                        <div id="chart-duration" :style="'width:'+ durElapseP"></div>
                    </div>
                    
                </div>
            </div>
            <!-- 书评 -->
            <div class="review-box">
                <div class="module-title">班级动态</div>
                <ul class="review-list">
                    <li v-for="(item,index) in reviewList" :key="index">
                        <div class="li-top clearfix">
                            <img :src="item.avatar ? item.avatar : $parent.headError" alt="" :onerror="$parent.headError" class="left">
                            <i class="left">{{item.trueName}}</i>
                            <span class="right" v-show="item.userId==$parent.myInfo.UserId" @click="deleClick(item,index)">删除</span>
                        </div>
                        <div class="li-main" @click="goReview(item)"> 
                            <p>{{item.experienceContent}}</p>
                        </div>
                        <div class="li-bottom clearfix">
                            <i class="left">{{item.createTime}}</i>
                            <span class="left">{{item.pageInterval}}</span>
                            <div :class="[item.isPraise ? 'islike like right' : 'like right']" @click="likeClick(item)">{{item.praiseCount}}</div>
                        </div>
                    </li>
                </ul>
                <transition name='fade'>
                    <div class="no-con small" v-show="noConShow">
                        <img src="@/assets/img/no-con.png" alt="">
                        <p>暂无书评...</p>
                    </div>
                </transition> 
                <div class="bottom-tips">{{bottomTip}}</div> 
            </div>
        </div>
        <div class="btn-box-main">
            <div class="btn-blue shadow2" @click="goDetail()">查看详情</div>
        </div>
        <!-- 选班级 -->
        <transition name='fade'>
            <div class="mask" v-show="classMaskShow">
                <div class="mask-close" @click="classClose()"></div>
                <transition name='slideup'>
                    <div class="class-box" v-show="classMaskShow">
                        <div class="grade-close" @click="classClose()"></div>
                        <ul>
                            <li :class="['left',{'ischose':classChose==index}]" v-for="(item,index) in classList" :key="index">
                                <span  @click="classChoseFun(item,index)">{{item.name}}</span>
                            </li>
                        </ul>
                    </div>
                </transition>
            </div>
        </transition>
        <!-- 提示弹窗 -->
        <Popup v-show="popupShow" :popupShow="popupShow" :popupType="2" :popupText="popupText" :popupTips="popupTips" @popupCancel="popupCancel" @popupSure="popupSure"></Popup>
    </div>
</template>

<script>
import { axGet,axPost } from '@/api/index'
import Popup from '@/components/Popup'
import echarts from 'echarts'

export default {
    name: "report",
    components:{
        Popup,
    },
    data(){
        return{
            userid:this.$parent.myInfo.UserId,
            bookid:this.$route.query.bookid,
            book:JSON.parse(sessionStorage.getItem("thisBook")),    //书本对象
            task:JSON.parse(sessionStorage.getItem("thisTask")),    //任务对象
            countday:0,         //当前时间
            reviewList:[],      //书评列表
            complete:[],        //今日完成列表
            incomplete:[],      //未完成列表
            // 选班
            thisClass:{},
            classChose:0,
            classList:[],
            classMaskShow:false,
            //提示弹窗
            popupShow:false,
            popupText:'确定要提前终止打卡任务吗？',
            popupTips:'所有学生的打卡任务都会终止',
            //图表
            numOption:{},
            durOption:{},
            numData:[],
            durData:[],
            numXdata:[],
            durXdata:[],
            numElapseP:'100%',
            durElapseP:'100%',
            // 分页
            noConShow:false,
            listPage:1,
            totalPage:1,
            bottomTip:'',
            isLoading:true,
        }
    },
    watch:{
        classMaskShow(newVal,oldVal){
            if(newVal){
                touchFalse() 
            }else{
                touchTrue()
            }
        },
    },
    created(){ 
        this.$parent.menuShow=false;
        /****** 验证登录 *****/ 
        if(!sessionStorage.getItem("myInfo")){
            this.$router.replace({path:'/',query: {}});
        }else{
            //班级
            let classcodeArr=this.task.checkInObject.split(',');
            let classnameArr=this.task.ClassName.split('·');
            let hasChose=false;
            let saveClass=sessionStorage.getItem("thisClass") ? JSON.parse(sessionStorage.getItem("thisClass")) : {}
            classcodeArr.forEach((code,i) => { 
                if(saveClass && saveClass.code==code){
                    console.log('hasChose')
                    hasChose=true
                }
                let list={
                    code:code,
                    name:classnameArr[i],
                }
                this.classList.push(list)
            });
            if(hasChose){
                this.classChose=parseInt(sessionStorage.getItem("classChose"))
                this.thisClass=saveClass
            }else{
                this.thisClass=this.classList[0]
            }
            

            this.getCountDown()
            if(this.countday>5){  //设置图表宽度
                this.numElapseP=6.2+(this.countday-5)*0.9+'rem'
                this.durElapseP=6.2+(this.countday-5)*0.9+'rem'
            }
            this.numData=new Array(this.countday).fill(0)
            this.durData=new Array(this.countday).fill(0)
            this.getNumber()
            this.getDuration()

            this.getTodayState()
            this.getReview(1)
        }
    },
    mounted(){
        // console.log(this.task)

    },
    destroyed(){
        touchTrue()
    },
    methods:{
        goToday(){
            if(this.complete.length>0 || this.incomplete.length>0){
                  this.$router.push({path:'/today',query: {}});          
            } 
        },
        goDetail(){
            this.$router.push({path:'/reportDetail',query: {bookid:this.bookid,classcode:this.thisClass.code}}); 
        },
        // 去书评详情
        goReview(item){
            sessionStorage.setItem("thisReview",JSON.stringify(item))
            this.$router.push({path:'/review',query: {bookid:this.bookid,reviewid:item.experienceId}});
        },
        // 班级选择
        classChoseFun(item,index){
            if(this.classChose!=index){
                this.classChose=index
                this.thisClass=item
                sessionStorage.setItem("classChose",index)
                sessionStorage.setItem("thisClass",JSON.stringify(item))

                this.numData=new Array(this.countday).fill(0)
                this.durData=new Array(this.countday).fill(0)
                this.numOption={}
                this.durOption={}
                this.getNumber()
                this.getDuration()

                this.complete=[]
                this.incomplete=[]
                this.getTodayState()
                
                this.reviewList=[]
                this.noConShow=false
                this.listPage=1
                this.totalPage=1
                this.bottomTip=''
                this.isLoading=true
                this.getReview(1)
                this.classMaskShow=false;
            }
        },
        classClose(){
            this.classMaskShow=false;
        },
        //今日完成
        getTodayState(){
            axGet('GetClassToDayCompletion', {
                TaskId:this.task.taskId,
                ClassCode:this.thisClass.code,
            }).then(res => {
                if(res.ResultCode==1 && res.Value){
                    res.Value.forEach((item,i)=>{
                        if(item.IsComplete){
                            this.complete.push(item)
                        }else{
                            this.incomplete.push(item)
                        }
                    })
                    sessionStorage.setItem("complete",JSON.stringify(this.complete))
                    sessionStorage.setItem("incomplete",JSON.stringify(this.incomplete))
                }
            })
        },
        optionFun(xList,dataList,dataName){
            let option = {
                color:'#cdd5dd',
                tooltip: { 
                },
                grid:{
                    left:0,                   
                    top:70,                         
                    right:0, 
                    bottom:40, 
                },
                xAxis: {
                    data:xList,
                    axisLabel:{       // x轴字体
                        color:'#666',
                        formatter: (value)=> {
                            return '第'+value+'天';
                        }
                    },  
                    axisLine:{        // 坐标轴
                        lineStyle:{   
                            color:'#f3f5f7'
                        }    
                    }, 
                    axisTick:{       //刻度线
                        show:false
                    },
                },
                yAxis: {
                    show : false,
                },
                series: [{
                    type: 'bar',
                    barWidth : 36, //柱图宽度
                    data: dataList,
                    itemStyle: {
                        emphasis: {
                            barBorderRadius:[6, 6, 0, 0]
                        },
                        normal: {
                            barBorderRadius:[6, 6, 0, 0],
                            label: {
                                show: true, 
                                position: 'top', //在上方显示
                                textStyle: { //数值样式
                                    // color:'#adb9c7',
                                    fontSize: 12,
                                },
                                formatter: (params) => {
                                    let str=''
                                    // if(params.value>0){
                                        str=params.value+dataName
                                    // }
                                    return str;
                                },
                            }
                        },
                    }
                }]
            };

            return option;
        },
        // 每日完成数
        getNumber(){
            axGet('GetClassDayCompleteCount', {
                TaskId:this.task.taskId,
                ClassCode:this.thisClass.code,
            }).then(res => {
                if(res.ResultCode==1){
                    this.numData=[]
                    this.numXdata=Object.keys(res.Value)
                    for(let item in res.Value){
                        let list=res.Value[item];
                        if(item==this.numXdata.length){
                            list={
                                value:res.Value[item],
                                itemStyle: {
                                    color: '#02affe',
                                }
                            }
                        }
                        this.numData.push(list)
                    }
                    var numChart = echarts.init(document.getElementById('chart-number'));
                    this.numOption=this.optionFun(this.numXdata,this.numData,'人');
                    numChart.setOption(this.numOption);

                }
            })
        },
        // 阅读平均时长
        getDuration(){
            axGet('GetClassDayAverageTaskMinute', {
                TaskId:this.task.taskId,
                ClassCode:this.thisClass.code,
            }).then(res => {
                if(res.ResultCode==1){
                    this.durData=[]
                    this.durXdata=Object.keys(res.Value)
                    for(let item in res.Value){
                        let list=Math.ceil(res.Value[item]/60);
                        if(item==this.durXdata.length){
                            list={
                                value:Math.ceil(res.Value[item]/60),
                                itemStyle: {
                                    color: '#02affe',
                                }
                            }
                        }
                        this.durData.push(list)
                    }
                    var durChart = echarts.init(document.getElementById('chart-duration'));
                    this.durOption=this.optionFun(this.durXdata,this.durData,'分钟');
                    durChart.setOption(this.durOption);
                }
            })
        },
        //请求书评列表
        getReview(page){
            axGet('GetClassExperienceList', {
                userId:this.userid,
                BookId: this.bookid,
                ClassCode:this.thisClass.code,
                PageIndex: page,
                PageSize:10,
            }).then(res => {
                if(res.ResultCode==1){
                    let listJson=res.Value.list;
                    listJson.forEach((item,i)=>{ 
                        this.reviewList.push(item)
                    })
                    if(page==1){
                        this.totalPage=res.Value.pageCount
                        this.reviewList.length==0 ? this.noConShow=true : this.noConShow=false
                    }
                    if(page<this.totalPage){
                        this.bottomTip='上拉加载更多'
                    }else{
                        this.bottomTip=''
                    }
                    this.isLoading=true;
                }else{
                    this.isLoading=false; 
                }
            })
        },
        // 删除
        deleClick(item,index){
            axGet('DeleteExperience', {
                UserId:this.userid,
                ExperienceId: item.experienceId,
            }).then(res => {
                if(res.ResultCode==1 && res.Value){
                    this.$LayerTip({
                        content:"删除成功",
                        time:1000,
                    });
                    this.reviewList.splice(index,1)
                }
            })
        },
        // 点赞
        likeClick(item){
            if(item.isPraise){
                this.removePraised(item)
            }else{
                this.addPraised(item)
            }
        },
        addPraised(item){
            axGet('PostPraise', {
                FromUserId: this.userid,
                ToUserId:item.userId,
                PraiseCategory:0,
                PraiseIdentity:item.experienceId, 
            }).then(res => {
                if(res.ResultCode==1){
                    item.isPraise=true;
                    item.praiseCount=parseInt(item.praiseCount)+1; 
                }
            })
        },
        removePraised(item){//取消赞
            axGet('CancelPraise', {
                FromUserId: this.userid,
                ToUserId:item.userId,
                PraiseCategory:0,
                PraiseIdentity:item.experienceId, 
            }).then(res => {
                if(res.ResultCode==1){
                    item.isPraise=false;
                    item.praiseCount=parseInt(item.praiseCount)-1; 
                }
            })
        },
        //任务时间
        getCountDown () {
            let time=this.task.createTime.slice(0,10)
            let countday = new Date().getTime() - new Date(time).getTime()
            this.countday = Math.ceil(countday / 1000 / 60 / 60 / 24)
        },
        // 关闭任务
        closeTask(){
            this.popupShow=true;
        },
        popupCancel(){
            this.popupShow=false;
        },
        popupSure(){
            axGet('StopTask', {
                UserId:this.userid,
                TaskId:this.task.taskId,
            }).then(res => {
                if(res.ResultCode==1){
                    this.popupShow=false;
                    this.$router.go(-1)
                    // this.$router.replace({path:'/bookDetail',query: {bookid:this.bookid}});
                }
            })
        },
        // 滚动加载   
        scrollLoad(){
            let bodyH = this.$refs['review'].clientHeight;
            let scrollH = this.$refs['review'].scrollTop;
            let listH = this.$refs['review'].scrollHeight;
            // console.log(bodyH,scrollH,listH)
            if(scrollH+bodyH+100>listH && this.isLoading){
                this.isLoading=false
                this.bottomTip='努力加载中...'
                // console.log(this.totalPage)
                this.listPage=this.listPage+1;
                if(this.listPage<this.totalPage || this.listPage == this.totalPage){
                    let page=this.listPage;
                    this.getReview(page)
                }else{
                    if(this.reviewList.length>0){
                        this.bottomTip='到达世界的边缘咯...'
                        console.log('没有更多数据')
                    }else{
                        this.bottomTip=''; 
                    } 
                }
            }
        },
    }
}
</script>
<style type="text/css" scoped>
.report{
    width: 100%;
    height: 100%;
    overflow: scroll;
}
.report-con{
    padding: 0.54rem 0.32rem 1.6rem;
}
.report-top{
    position: relative;
    padding-bottom: 0.4rem;
}
.report-top span{
    line-height: 1;
    padding-right: 0.4rem;
    font-size: 0.36rem;
    font-weight: bold;
    background: url(../../assets/img/icon/change-b.png) no-repeat right center;
    background-size: 0.28rem 0.28rem;
}
.report-top i{
    color: #02affe;
    font-size: 0.26rem;
}
.task-book{
    padding: 0.4rem 0 0.4rem 0.38rem;
    border-radius: 0.3rem;
    
}
.book-img{
    width: 1.6rem;
    height: 2.14rem;
    border-radius: 0.2rem;
}
.book-info{
    height: auto;
    padding-left: 0.48rem;
    max-width: 4rem;
}
.task-name{
    font-size: 0.36rem;
    line-height: 1;
    padding: 0.22rem 0;
    font-weight: bold;
    color: #000;
    word-wrap: break-word;
    word-break: normal;
}
.task-book .author{
    font-size: 0.26rem;
    color: #666;
    line-height: 1;
    word-wrap: break-word;
    word-break: normal;
}
.task-read{
    color: #999;
    padding-top: 0.32rem;
}
.task-day{
    width: 1.4rem;
}
.task-time{
    padding-left: 0.48rem;
}
.task-read em{
    display: block;
    font-size: 0.3rem;
    font-weight: bold;
}
.task-read span{
    display: block;
}
.task-day span{
    border-right:1px solid #e0e0e0;
}
.book-box{
    padding-bottom: 0.6rem;
}
.todaynum{
    display: inline-block;
    padding-right: 0.62rem;
    height: 0.4rem;
    line-height: 0.4rem;
    color: #02affe;
    font-size: 0.32rem;
    background: url(../../assets/img/icon/arrow-b.png) no-repeat right bottom;
    background-size: 0.4rem 0.4rem;
}
.review-box{
    padding-top: 0.7rem;
    font-size: 0.3rem;
}
.chart-box{
    padding:0 0.32rem;
    border-radius: 0.3rem;
    background: no-repeat left 0.36rem;
    background-size: auto 0.45rem;
    margin-top: 0.3rem;
    position: relative;
    box-sizing: border-box;
}
.chart-box h4{
    font-size: 0.3rem;
    font-weight: bold;
    position: absolute;
    top: 0.44rem;
    left: 0.4rem;
    line-height: 1;
}
.chart-number{
    background-image: url(../../assets/img/main/chart-bg1.png);
}
.chart-duration{
    background-image: url(../../assets/img/main/chart-bg2.png);
}
.chart-card{
    width: 100%;
    height: 4rem;
    overflow-x: scroll;
    overflow-y: hidden;
}
#chart-number{
    width: 100%;
    height: 4rem;
}
#chart-duration{
    width: 100%;
    height: 4rem;
}
</style>